/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.exception;

import org.tianyun.cloud.common.constants.ResponseCode;
import org.tianyun.cloud.common.dto.RestResult;
import org.tianyun.cloud.common.dto.RestResult.RestResultBuilder;
import org.tianyun.cloud.ext.i18n.I18nMessageSource;

/**
 * 默认的异常处理器
 *
 * @auther ebert_chan
 */
public class ExceptionDefaultResolver implements ExceptionContextAware {

    private I18nMessageSource i18nMessageSource;

    public ExceptionDefaultResolver(I18nMessageSource i18nMessageSource) {
        setI18nMessageSource(i18nMessageSource);
    }

    public I18nMessageSource getI18nMessageSource() {
        return i18nMessageSource;
    }

    public void setI18nMessageSource(I18nMessageSource i18nMessageSource) {
        this.i18nMessageSource = i18nMessageSource;
    }

    /*
     * @see org.tianyun.cloud.core.exception.ExceptionHandler#feedback(java.lang. Throwable)
     */
    @Override
    public Object feedback(Throwable throwable) {
        if (throwable instanceof BusinessException) {
            BusinessException e = (BusinessException) throwable;
            return this.feedback(e.getCode(), e.getArgs());
        }

        if (throwable instanceof SystemException) {
            SystemException e = (SystemException) throwable;
            return this.feedback(ResponseCode.SYSTEM_EXCEPTION, e.getCode());
        }

        return this.feedback(ResponseCode.BUSY_EXCEPTION);
    }

    /*
     * @see org.tianyun.cloud.core.exception.ExceptionContextAware#feedback(java.lang .String)
     */
    @Override
    public Object feedback(String code, Object... args) {

        String message = getI18nMessageSource().getMessage(code, args);

        if (message == null && args != null && args.length == 1 && args[0] != null && args[0] instanceof String) {
            message = (String) args[0];
        }

        RestResultBuilder<?> builder = RestResultBuilder.instance();
        builder.failure(code, message);
        RestResult<?> result = builder.build();

        return result;
    }

}
